import logging

from django import http
from django.shortcuts import render
from django.views import View
from django.core.cache import cache

# Create your views here.
from areas.models import Areas
from meiduo_mall.utils.response_code import RETCODE

logger = logging.getLogger('django')


class AreasView(View):
    """ 省市区三级联动 """

    def get(self, request):
        area_id = request.GET.get('area_id')
        # 全部数据
        if not area_id:
            province_list = cache.get('province_list')
            if not province_list:
                try:
                    province_model_list = Areas.objects.filter(parent__isnull=True)
                    province_list = [item.to_json() for item in province_model_list]
                    cache.set('province_list', province_list, 3600) # 缓存
                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '查询省份数据错误'})
            # 响应
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'province_list': province_list})
        # 指定id
        else:
            sub_data = cache.get(f'sub_area_{area_id}')
            if not sub_data:
                try:
                    parent_model = Areas.objects.get(id=area_id)
                    sub_model_list = parent_model.subs.all()  # id获取

                    sub_list = [item.to_json() for item in sub_model_list]
                    sub_data = {
                        "id": parent_model.id,
                        "name": parent_model.name,
                        "subs": sub_list
                    }
                    cache.set(f'sub_area_{area_id}',sub_data,3600)
                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '查询省份数据错误'})
            # 响应
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'sub_data': sub_data})